﻿using SF.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SF.Ucenter.admin.goods
{
    public partial class goods_edit : Web.UI.ManagePage
    {
        private string action = DTEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;
        private List<Model.sf_goods_amounts> amountList = null;//库存集合
        //页面加载事件
        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = DTRequest.GetQueryString("action");

            if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
            {
                this.action = DTEnums.ActionEnum.Edit.ToString();//修改类型
                this.id = DTRequest.GetQueryInt("id");
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    return;
                }
                if (!new BLL.sf_goods_info().Exists(this.id))
                {
                    JscriptMsg("商品不存在或已被删除！", "back");
                    return;
                }
            }
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("goods_list", DTEnums.ActionEnum.View.ToString()); //检查权限

                //绑定 商品类型
                BLL.sf_goods_alltype bll = new BLL.sf_goods_alltype();
                string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString(); 
                if (string.IsNullOrEmpty(templatesNum))
                {
                    JscriptMsg("请先在商品管理中选择模版！", "/admin/modeconfig/malltemplet_list.aspx");
                    return;
                }
                string where = new BLL.sf_modeconfig().GetModel("settingNum='" + templatesNum + "'").goodstype_onshelf;
                DataTable dt = bll.GetList("typeNum='" + where + "'").Tables[0];
                this.ddlGoodsTypeId.Items.Clear();
                this.ddlGoodsTypeId.Items.Add(new ListItem("请选择类型...", ""));
                foreach (DataRow dr in dt.Rows)
                {
                    this.ddlGoodsTypeId.Items.Add(new ListItem(dr["typeName"].ToString().Trim(), dr["typeNum"].ToString()));
                }

                if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
                {
                    //禁变更 所属类型 编辑
                    ddlGoodsTypeId.Enabled = false;
                    //禁用 商品编号 编辑
                    txtGoodsNum.Enabled = false;
                    ShowInfo(this.id);
                }
                else
                {
                    txtGoodsNum.Attributes.Add("ajaxurl", "../../tools/goods_ajax.ashx?action=goods_list_num_validate");
                }
            }
        }

        #region 绑定类别
        private void TreeBind(string typeid)
        {
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string busnieseNum = mgr.busnieseNum.ToString();
            string appNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            string templatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();
            BLL.sf_goods_types bll = new BLL.sf_goods_types();
            DataTable dt = bll.GetList(0, "goodsTypeNum='" + typeid + "' and " + Utils.getWhereByInfo(busnieseNum,appNum,templatesNum));

            this.ddlCategoryId.Items.Clear();
            this.ddlCategoryId.Items.Add(new ListItem("请选择类别...", ""));
            foreach (DataRow dr in dt.Rows)
            {
                string typeNum = dr["typeNum"].ToString();
                int ClassLayer = int.Parse(dr["class_layer"].ToString());
                string Title = dr["name"].ToString().Trim();

                if (ClassLayer == 1)
                {
                    this.ddlCategoryId.Items.Add(new ListItem(Title, typeNum));
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    this.ddlCategoryId.Items.Add(new ListItem(Title, typeNum));
                }
            }
        }
        #endregion

        #region 赋值操作
        private void ShowInfo(int _id)
        {
            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            Model.sf_goods_info model = bll.GetModel(_id);
            TreeBind(model.goodsTypeNum);
            #region sf_goods_info basic data
            ddlCategoryId.SelectedValue = model.typeNum;
            ddlGoodsTypeId.SelectedValue = model.goodsTypeNum;
            txtGoodsNum.Text = model.goodsNum;
            txtName.Text = model.names;
            if (model.ishot == 1)
                rblStatus_0.Checked = true;
            else if (model.ishot == 2)
                rblStatus_1.Checked = true;
            else if (model.ishot == 3)
                rblStatus_2.Checked = true;
            //txtValidTime.Text = model.validTime;
            field_control_market_price.Text = model.costPrice.ToString();
            field_control_sell_price.Text = model.salesPrice.ToString();
            field_control_get_price.Text = model.showPrice.ToString();
            txtSortId.Text = model.sort.ToString();
            txtBrandName.Text = model.brandName;
            txtPlace.Text = model.place;
            txtUnit.Text = model.unit;
            txtSuitPerson.Text = model.suitPerson;
            txtAddTime.Text = model.times;

            txtImgUrl.Text = model.showImgs;
            imgHeadPic.ImageUrl = model.showImgs;
            hidFocusPhoto.Value = model.showImgs;
            #endregion

            BLL.sf_goods_img imgBll = new BLL.sf_goods_img();
            //获取到对应的图片列表
            DataSet ds = imgBll.GetList("  goodsNum='" + model.goodsNum + "'");
            if (ds.Tables[0].Rows.Count > 0)
            {
                rptAlbumList.DataSource = ds.Tables[0];
                rptAlbumList.DataBind();
            }
            if (!model.goodsTypeNum.Equals("maquillage"))
            {
                BLL.sf_goods_amounts amountsBll = new BLL.sf_goods_amounts();
                //获取到商品对应 库存列表 提交给js使用
                amountList = amountsBll.GetModelList("  goodsNum='" + model.goodsNum + "'");
                string res = subStringAmount(amountList, model.goodsTypeNum.ToString());
                string jsApp = "editset(\"" + res + "\", \"" + ddlGoodsTypeId.SelectedValue.ToString() + "\")";
                ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsSet", jsApp, true);
            }
            else
            {
                amountNum.Text = model.num.ToString();
                string jsApp = "showLine(\"" + ddlGoodsTypeId.SelectedValue.ToString() + "\")";
                ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsSet", jsApp, true);
            }
        }
        #endregion


        #region 增加操作
        private int DoAdd()
        {
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string strBusnieseNum = mgr.busnieseNum.ToString();
            string strAppNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            string strTemplatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            //&&注意前台 TextBox 设置 ReadOnly 之后 后台通过ID 直接获取值
            //&&不能获取到
            int result = 1;
            Model.sf_goods_info model = new Model.sf_goods_info();
            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            try
            {
                #region basic filed
                model.busnieseNum = strBusnieseNum;
                model.appNum = strAppNum;
                model.templatesNum = strTemplatesNum;
                model.typeNum = ddlCategoryId.SelectedItem.Value;
                model.goodsTypeNum = ddlGoodsTypeId.SelectedValue;
                model.goodsNum = txtGoodsNum.Text.Trim();
                model.names = txtName.Text.Trim();

                model.num = model.goodsTypeNum.Equals("maquillage") ? Convert.ToInt32(amountNum.Text) : 0;

                if (rblStatus_0.Checked)
                    model.ishot = 1;
                else if (rblStatus_1.Checked)
                    model.ishot = 2;
                else if (rblStatus_2.Checked)
                    model.ishot = 3;
                model.validTime = "";
                //model.validTime = txtValidTime.Text.Trim();
                model.showPrice = 0;
                model.costPrice = Utils.StrToDecimal(field_control_market_price.Text.Trim(), 0);
                model.salesPrice = Utils.StrToDecimal(field_control_sell_price.Text.Trim(), 0);
                model.showPrice = Utils.StrToDecimal(field_control_get_price.Text.Trim(), 0);
                model.sort = Utils.StrToInt(txtSortId.Text.Trim(), 99);
                model.brandName = txtBrandName.Text.Trim();
                model.place = txtPlace.Text.Trim();
                model.unit = txtUnit.Text.Trim();
                model.suitPerson = txtSuitPerson.Text.Trim();
                model.times = DTRequest.GetFormStringValue(Request.Form["txtAddTime"].Trim(), DateTime.Now.ToString("yyyy-MM-dd"));
                model.remark = "";
                model.showImgs = Request.Form["txtImgUrl"].Trim();
                model.status = 1;
                #endregion

                #region pic upload
                BLL.sf_goods_img imgBll = new BLL.sf_goods_img();
                List<Model.sf_goods_img> ls = new List<Model.sf_goods_img>();
                string[] albumArr = Request.Form.GetValues("hid_photo_name");
                string[] remarkArr = Request.Form.GetValues("hid_photo_remark");

                if (albumArr != null && albumArr.Length > 0)
                {
                    for (int i = 0; i < albumArr.Length; i++)
                    {
                        string[] imgArr = albumArr[i].Split('|');
                        if (imgArr.Length == 2 || imgArr.Length == 3)
                        {
                            ls.Add(new Model.sf_goods_img { busnieseNum = mgr.busnieseNum, appNum = strAppNum, templatesNum = strTemplatesNum, goodsNum = model.goodsNum, imgName = remarkArr[i], imgUri = imgArr[1], id = Convert.ToInt32(imgArr[0]) });
                        }
                    }
                    model.goodsImgs = ls;
                }
                #endregion

                if (bll.Add(model) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加商品内容:" + model.names); //记录日志
                    result = 0;
                }
            }
            catch (Exception)
            {
                result = - 1;
            }
            return result;
        }
        #endregion

        #region 修改操作
        private int DoEdit(int _id)
        {
            int result = 1;
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            string strBusnieseNum = mgr.busnieseNum.ToString();
            string strAppNum = Session[DTKeys.SESSION_APP_INFO].ToString();
            string strTemplatesNum = Session[DTKeys.SESSION_TEMPLATES_INFO].ToString();

            BLL.sf_goods_info bll = new BLL.sf_goods_info();
            Model.sf_goods_info model = bll.GetModel(_id);
            try
            {
                #region basic data
                model.typeNum = ddlCategoryId.SelectedItem.Value;
                model.goodsTypeNum = ddlGoodsTypeId.SelectedValue;
                model.goodsNum = txtGoodsNum.Text.Trim();
                model.names = txtName.Text.Trim(); 

                model.num = model.goodsTypeNum.Equals("maquillage") ? Convert.ToInt32(amountNum.Text) : 0;

                if (rblStatus_0.Checked)
                    model.ishot = 1;
                else if (rblStatus_1.Checked)
                    model.ishot = 2;
                else if (rblStatus_2.Checked)
                    model.ishot = 3;
                //model.validTime = txtValidTime.Text.Trim();
                model.validTime = "";
                model.showPrice = 0;
                model.costPrice = Utils.StrToDecimal(field_control_market_price.Text.Trim(), 0);
                model.salesPrice = Utils.StrToDecimal(field_control_sell_price.Text.Trim(), 0);
                model.showPrice = Utils.StrToDecimal(field_control_get_price.Text.Trim(), 0);
                model.sort = Utils.StrToInt(txtSortId.Text.Trim(), 99);
                model.brandName = txtBrandName.Text.Trim();
                model.place = txtPlace.Text.Trim();
                model.unit = txtUnit.Text.Trim();
                model.suitPerson = txtSuitPerson.Text.Trim();
                model.times = txtAddTime.Text.Trim();
                model.remark = "";
                model.showImgs = txtImgUrl.Text;
                model.showImgs = Request.Form["txtImgUrl"].Trim();
                #endregion

                #region pic upload
                BLL.sf_goods_img imgBll = new BLL.sf_goods_img();
                List<Model.sf_goods_img> ls = new List<Model.sf_goods_img>();
                string[] albumArr = Request.Form.GetValues("hid_photo_name");
                string[] remarkArr = Request.Form.GetValues("hid_photo_remark");

                if (albumArr != null && albumArr.Length > 0)
                {
                    for (int i = 0; i < albumArr.Length; i++)
                    {
                        string[] imgArr = albumArr[i].Split('|');
                        if (imgArr.Length == 2 || imgArr.Length == 3)
                        {
                            ls.Add(new Model.sf_goods_img { busnieseNum = mgr.busnieseNum, appNum = strAppNum, templatesNum = strTemplatesNum, goodsNum = model.goodsNum, imgName = remarkArr[i], imgUri = imgArr[1], id = Convert.ToInt32(imgArr[0]) });
                        }
                    }
                    model.goodsImgs = ls;
                }
                #endregion

                if (bll.Update(model))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改商品内容:" + model.names); //记录日志
                    result = 0;
                }
            }
            catch (Exception)
            {
                result = - 1;
            }
            return result;
        }
        #endregion


        //保存
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("goods_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                int res = DoEdit(this.id);
                if (res == 1)
                {
                    JscriptMsg("保存过程中发生错误啦！", "");
                    return;
                }
                else if (res == -1)
                {
                    ddlGoodsTypeId.SelectedValue = "";
                    JscriptShow("商品提示", "请输入合理的库存！", "");
                    return;
                }
                //string text = "savelist(\"" + txtGoodsNum.Text.Trim() + "\", \"" + this.hiddenLists.Value + "\");";
                //ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsSave", text, true);
                JscriptMsg("修改信息成功！", "goods_list.aspx");
            }
            else //添加
            {
                ChkAdminLevel("goods_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
                int res = DoAdd();
                if (res == 1)
                {
                    JscriptMsg("保存过程中发生错误啦！", "");
                    return;
                }
                else if (res == -1)
                {
                    ddlGoodsTypeId.SelectedValue = "";
                    JscriptShow("商品提示", "请输入合理的库存！", "");
                    return;
                }
                //string text = "savelist(\"" + txtGoodsNum.Text.Trim() + "\");";
                //ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsSave", text, true);
                JscriptMsg("添加信息成功！", "goods_list.aspx");
            }
        }

        /// <summary>
        /// 商品所属类型 下拉选择 
        /// </summary>
        protected void ddlGoodsTypeId_SelectedIndexChanged(object sender, EventArgs e)
        {
            //绑定类别
            if (!string.IsNullOrEmpty(ddlGoodsTypeId.SelectedValue.ToString()))
            {
                TreeBind(ddlGoodsTypeId.SelectedValue.ToString());
                string msbox = "showLine(\"" + ddlGoodsTypeId.SelectedValue.ToString() + "\")";
                ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsLine", msbox, true);
            }
        }

        /// <summary>
        /// 库存信息拼接字符串
        /// 交由前台js使用
        /// </summary>
        /// <param name="list">库存信息集合</param>
        /// <returns></returns>
        public string subStringAmount(List<Model.sf_goods_amounts> list, string goodsTypeNum)
        {
            Model.manager mgr = Session[DTKeys.SESSION_ADMIN_INFO] as Model.manager;
            BLL.sf_goods_color colorBll = new BLL.sf_goods_color();
            List<Model.sf_goods_color> colors = colorBll.GetModelList("goodsTypeNum='" + goodsTypeNum + "' and " + Utils.getWhereByInfo(mgr.busnieseNum, Session[DTKeys.SESSION_APP_INFO].ToString(), Session[DTKeys.SESSION_TEMPLATES_INFO].ToString()));
            string msg = "";
            int inputId = 0;
            foreach (Model.sf_goods_amounts amount in list)
            {
                for (int i = 0; i < colors.Count; i++)
                {
                    if (amount.colorId == colors[i].Id)
                    {
                        inputId = i;
                    }
                }
                msg += amount.sizeId + "^" + inputId + "_" + amount.colorId + "_" + amount.amount + ",";
            }
            return msg;
        }

    }
}